package com.chenyaohua.file;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class CopySimpleFileVisitor  extends SimpleFileVisitor<Path> {

    private Path sourcePath;
    private Path targetPath;

    public CopySimpleFileVisitor (Path sourcePath, Path targetPath) {
        this.sourcePath = sourcePath;
        this.targetPath = targetPath;
    }

    @Override
    public FileVisitResult visitFile (Path file, BasicFileAttributes attrs) throws IOException {
        //计算相对路径
        Path relativize = sourcePath.relativize(file);
        //计算新路径
        Path resolve = targetPath.resolve(relativize);

        Files.createDirectories(resolve.getParent());

        Files.copy(file,resolve, StandardCopyOption.REPLACE_EXISTING);
        return super.visitFile(file, attrs);
    }

    @Override
    public FileVisitResult visitFileFailed (Path file, IOException exc) throws IOException {
        exc.printStackTrace();
        return FileVisitResult.CONTINUE;
    }
}
